package com.example.choupaiapp.main.util;

import android.content.Context;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.widget.Toast;

import com.example.choupaiapp.common.util.ContextUtil;
import com.example.choupaiapp.main.callback.WechatCallBack;
import com.example.choupaiapp.main.constant.Config;
import com.tencent.mm.opensdk.modelmsg.SendAuth;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.tencent.mm.opensdk.openapi.WXAPIFactory;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by ASUS on 2018/11/5.
 */

public class WechatLoginUtil {

    public static IWXAPI api;
    public WechatCallBack wechatCallBack;
    private static WechatLoginUtil wechatLoginUtil = null;

    private WechatLoginUtil(){
        api = WXAPIFactory.createWXAPI(ContextUtil.getContext(), Config.WEIXIN_APP_ID, true);
    }

    public static WechatLoginUtil getInstance(){
        if(wechatLoginUtil==null){
            wechatLoginUtil = new WechatLoginUtil();
        }
        return wechatLoginUtil;
    }

    public void wechatLogin(){
        SendAuth.Req req = new SendAuth.Req();
        req.scope = "snsapi_userinfo";
        req.state = "wechat_sdk_login";
        api.registerApp(Config.WEIXIN_APP_ID);
        api.sendReq(req);
    }

    public boolean isWeChatAppInstalled() {
        if (api.isWXAppInstalled()) {
            return true;
        } else {
            isAvilible(ContextUtil.getContext(), "com.tencent.mm");
        }
        return false;
    }

    public boolean isAvilible(Context context, String packageName) {
        // 获取packagemanager
        final PackageManager packageManager = context.getPackageManager();
        // 获取所有已安装程序的包信息
        List<PackageInfo> packageInfos = packageManager.getInstalledPackages(0);
        // 用于存储所有已安装程序的包名
        List<String> packageNames = new ArrayList<String>();
        // 从pinfo中将包名字逐一取出，压入pName list中
        if (packageInfos != null) {
            for (int i = 0; i < packageInfos.size(); i++) {
                String packName = packageInfos.get(i).packageName;
                packageNames.add(packName);
            }
        }
        // 判断packageNames中是否有目标程序的包名，有TRUE，没有FALSE
        return packageNames.contains(packageName);
    }

    public void setWechatCallBack(WechatCallBack callBack){
        wechatCallBack = callBack;
    }
}
